package com.miyake.loveviewweb.client.viewer.table;

import java.util.List;

import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.Widget;
import com.miyake.loveviewweb.client.viewer.table.ContentGetter.DataModelHandler;
import com.miyake.loveviewweb.shared.XsvToDataColumnModel;
import com.miyake.loveviewweb.shared.model.DataColumnModel;
import com.miyake.loveviewweb.shared.model.DataModel;

public class XCV extends TextArea implements ITable {

    public XCV(DataModel dataModel, final String delimiter) {
        
        this.setSize("100%", "150px");
        
        new ContentGetter(dataModel, new DataModelHandler() {

            public void onUpdate(DataModel dataModel) {
                String csv = "";
                int col = 0;
                int cols = dataModel.getXyDataBody().getDataColumn().size();
                for (DataColumnModel model : dataModel.getXyDataBody().getDataColumn()) {
                    csv += model.getHeader();
                    if (col++ < cols-1) {
                        csv += delimiter;
                    }
                }

                csv += "\n";
                
                List<String[]> d = new TableDataSwapper(dataModel.getXyDataBody().getDataColumn()).get();
                for (String[] arr : d) {
                    col = 0;
                    for (String s : arr) {
                        csv += s;
                        if (col++ < cols-1) {
                            csv += delimiter;
                        }
                    }
                    
                    csv += "\n";
                }
                

                setText(csv);
            }
            
        });
    }

    public Widget getUiWidget() {
        return this;
    }

    public List<DataColumnModel> getDataColumnList() {
        XsvToDataColumnModel converter = new XsvToDataColumnModel(this.getText(), true);
        return converter.getDataColumnModels();
    }
}
